<?php

/**
 * Domyslna klasa DAL
 *
 * @author pawel
 */
abstract class DefaultDAL {

    private static $cacheTime;
    private static $cachePath;
    private static $cacheId;

    public static function DefaultRemoveDuplicate($objClassTable, $objClassTablePK, $optClassTableChangeArray, $changeDictionaryTo = null) {
	$db = Registry::Get('db');

	$db->BeginTransaction();
	// znajdujemy wszytkie duplikaty od otrzymanego id
	//pobieramy nazwe
	$sql = "SELECT name FROM $objClassTable WHERE $objClassTablePK = $changeDictionaryTo";
	$stmt = $db->prepare($sql)
		->execute();

	$array = $stmt->fetchAllAssoc();

	$name = $array[0]['name'];
	//znajdujemy wszytkie duplikaty tego sameogo pola
	$sql = "SELECT $objClassTablePK FROM $objClassTable WHERE name = '$name' AND $objClassTablePK != $changeDictionaryTo";

	$stmt = $db->prepare($sql)
		->execute();

	$array = $stmt->fetchAllAssoc();

	// dodajemy wszytkie id tych samych rekordkow do tablicy
	$idDuplicateArray = array();
	for ($i = 0; $i < count($array); $i++) {
	    $idDuplicateArray[] = $array[$i][$objClassTablePK];
	}

	//var_dump($idDuplicateArray);
	self::DefaultMoveDictionary($objClassTable, $objClassTablePK, $optClassTableChangeArray, $idDuplicateArray, $changeDictionaryTo);

	$db->CommitTransaction();
    }

    public static function DefaultMoveDictionary($objClassTable, $objClassTablePK, $optClassTableChangeArray, $changeDictionary = array(), $changeDictionaryTo = null) {
	$db = Registry::Get('db');

	$db->BeginTransaction();

	if (count($changeDictionary) > 0)
	    foreach ($optClassTableChangeArray as $key => $value) {
		// pierwsze zmienic wszytkie istnijace z changedictionary na docelowe
		if ($value == "nm_physician") {
		    $sql = "UPDATE $value SET $objClassTablePK=$changeDictionaryTo,reload=1 WHERE $objClassTablePK ";
		} else {
		    $sql = "UPDATE $value SET $objClassTablePK=$changeDictionaryTo WHERE $objClassTablePK ";
		}

		$in = "";
		if (count($changeDictionary) == 1) {
		    $sql .= " = " . $changeDictionary[0];
		} else if (count($changeDictionary) > 1) {
		    $sql .= " IN (";
		    foreach ($changeDictionary as $key => $value) {
			$in.=$value . ", ";
		    }
		    $in = substr($in, 0, strlen($in) - 2);
		    $sql.=$in;
		    $sql.=")";
		}
		$stmt = $db->prepare($sql)
			->execute();
	    }

	//usuniecie wszytkich z changedictionary
	if (count($changeDictionary) > 0)
	    foreach ($changeDictionary as $key => $value) {
		$dalData = new DalData();
		$dalData->setObjClassTable($objClassTable);
		$dalData->setObjClassTablePK($objClassTablePK);
		$dalData->setObj($value);
		self::DefaultDelete($dalData);
	    }
	$db->CommitTransaction();
    }

    /**
     *
     * Znajduje duplikaty (takie same pola w tabeli slowników)
     *
     * @param <type> $optClass
     * @param <type> $objClassTable
     * @param <type> $objClassName
     */
    public static function DefaultFindDuplicate($optClass, $objClassTable, $objClassName, $duplicateField) {
	$db = Registry::Get('db');

	$queryCacheName = $objClassName . "_" . __FUNCTION__ . "_" . md5($objClassTable);

	if (QUERYCACHE_ENABLE == true && isset(QueryCacheTemp::$cacheQuery[$queryCacheName])) {
	    $sql = QueryCacheTemp::$cacheQuery[$queryCacheName];
	} else {
	    $select = " " . SQL::ToSelect($optClass) . " , count($duplicateField) as countField ";

	    $sql = " SELECT $select FROM " . $objClassTable . " WHERE 1=1";

	    $q = new QueryCache($queryCacheName, $sql);
	}
	$sql.=" GROUP BY $duplicateField HAVING countField>1";

	/*
	  $sql .= ( $sortBy ? " ORDER BY $sortBy " : "").
	  ( $limit ? " LIMIT " . $limit : "").
	  " ";
	 */

	$stmt = $db->prepare($sql)
		->execute();


	$array = $stmt->fetchAllAssoc();

	$done = array();

	for ($i = 0; $i < count($array); $i++) {
	    $className = $objClassName;
	    $obj = new $className();
	    $obj->FromArray($array[$i], 1);
	    $obj->setCountField($array[$i]['countField']);
	    $done[] = $obj;
	}
	return $done;
    }

    /**
     * Wykonanie zapytania
     *
     * @param klasa opcjonalna $optClass
     * @param tablica $objClassTable
     * @param nazwa klasy $objClassName
     * @param tablica pol do where $data
     * @param tablica pol do zapytania $queryFields
     * @param limit do zapytania $limit
     * @param sortowanie do zapytania $sortBy
     * @param opcjonalna liczba rekordow w odpowiedzi(true/false) $count
     * @return array
     */
    public static function DefaultGetResult(DalData $dalObj, $showSQL=false) {

	if (!self::CacheControll($dalObj)) {
	    $joinString = null;
	    $selectString = null;

	    if (is_array($dalObj->getJoin())) {
		foreach ($dalObj->getJoin() as $key => $value) {
		    list($key, $alias) = array_merge(explode(' ', $key), array(null)); //aliasy w joinach
		    if (trim(SQL::ToSelect($key, $dalObj->getQueryFields(), $alias)) != "") //aliasy w joinach
			$selectString .="," . SQL::ToSelect($key, $dalObj->getQueryFields(), $alias); //aliasy w joinach
		    $joinString .= $value;
		}
	    }

	    $db = Registry::Get($dalObj->getDatabaseType());

	    if ($dalObj->getCount() == true) {
		$select = "count(*) as count";
	    } else if ($dalObj->getAsCount()) {
		$select = $dalObj->getAsCount();
	    } else {
		$select = " " . SQL::ToSelect($dalObj->getOptClass(), $dalObj->getQueryFields()) . " " . $selectString . " " . $dalObj->getSelectFieldsQuery();
	    }


	    if ($dalObj->getOperationType() != 'SELECT')
		$select = null;


	    $updatePart = null;

	    if ($dalObj->getOperationType() != 'UPDATE') {
		$queryPart2 = " FROM ";
	    } else {
		$queryPart2 = null;
		$updateQuery = array();


		foreach ($dalObj->getUpdateFileldArray() as $key => $value) {
		    $updateQuery[] = $key . "='" . $db->Escape($value) . "'";
		}
		$updatePart = " SET " . implode(',', $updateQuery);
	    }


	    $sql = $dalObj->getOperationType() . " " . $select . $queryPart2 . $dalObj->getObjClassTable() . " " . $updatePart . $joinString . " WHERE 1=1 ";

	    $q = new QueryCache($queryCacheName, $sql);
	    
	    foreach ($dalObj->getCondition() as $key => $valueArray) {
		if ($key == "id")
		    $key = "id_" . $dalObj->getObjClassTable();

		if (!is_array($valueArray))
		    $valueArray = array($valueArray);

		foreach ($valueArray as $value) {
		    if (is_array($value)) {
			if (!isset($value['split']))
			    $value['split'] = ' AND ';

			$sql .= ( is_numeric($value['value']) || $value ? " " . $value['split'] . " " . $key . " " . $value['condition'] . " " . $value['value'] : "");
		    }
		    else
			$sql .= ( is_numeric($value) || $value ? " AND " . $key . " = '" . $value . "'" : "");
		}
	    }
	    $sql .=
		    ( trim($dalObj->getGroupBy()) ? " GROUP BY " . $dalObj->getGroupBy() : "") .
		    ( (trim($dalObj->getHaving()) && $dalObj->getCount() == false) ? " HAVING " . $dalObj->getHaving() : "") .
		    ( trim($dalObj->getSortBy()) ? " ORDER BY " . $dalObj->getSortBy() : "") .
		    ( $dalObj->getLimit() ? " LIMIT " . $dalObj->getLimit() : "") .
		    " ";
	    if ($showSQL) {
		$sqlForDisplay = Utils::SQLFormat($sql);
		Utils::ArrayDisplay($sqlForDisplay);
	    }
	    try {
		$stmt = $db->prepare($sql);

		if ($dalObj->getCacheTime() > 0) {
		    $stmt->CacheStart($dalObj->getCacheTime());
		}
	    } catch (MysqlException $e) {
		
	    }



	    $stmt->execute();
	    if ($dalObj->getOperationSettings('fetchResult')) {
		$array = $stmt->fetchAllAssoc();

		//Utils::ArrayDisplay($sql);
		if ($dalObj->getCount() == true) {
		    if (strlen($dalObj->getGroupBy()) > 0
		    )
			return count($array);
		    return $array[0]['count'];
		}elseif ($dalObj->getAsCount()) {
		    if (strlen($dalObj->getGroupBy()) > 0
		    )
			return count($array);
		    return $array[0][$dalObj->getAsCount()];
		}
		$done = array();

		for ($i = 0; $i < count($array); $i++) {
		    $className = $dalObj->getObjClassName();
		    $obj = new $className();
		    $obj->FromArray($array[$i], 1);

		    foreach ($dalObj->getSelectFields() as $key => $value) {
			$func = "set" . $key;
			$obj->$func($array[$i][$key]);
		    }
		    if (is_array($dalObj->getJoin()))
			foreach ($dalObj->getJoin() as $key => $value) {
			    list($key, $alias) = array_merge(explode(' ', $key), array(null)); //aliasy w joinach
			    $objArray = new $key();
			    $objArray->FromArray($array[$i], 1, $alias); //aliasy w joinach
//							$strFunciton="set" . $key;
//							$obj->$strFunciton($objArray);
			    $fLetter = $key{0};
			    $key{0} = strtolower($fLetter);
			    $obj->$key = $objArray;
			}
		    $done[] = $obj;
		}
		if ($dalObj->getCacheObject()) {
		    self::CacheWriter($done);
		}
	    } else {
		$done = true;
	    }
	    return $done;
	} else {
	    return self::CacheReader();
	}
    }

    public static function DefaultGetResultByLink(DalData $dalObj) {
	if (!self::CacheControll($dalObj)) {
	    $joinString = null;
	    $selectString = null;

	    if (is_array($dalObj->getJoin())) {
		foreach ($dalObj->getJoin() as $key => $value) {
		    if (trim(SQL::ToSelect($key, $dalObj->getQueryFields())) != "")
			$selectString .="," . SQL::ToSelect($key, $dalObj->getQueryFields());
		    $joinString .= $value;
		}
	    }

	    $db = Registry::Get($dalObj->getDatabaseType());

	    $queryCacheName = $dalObj->getObjClassName() . "_" . $dalObj->getObjClassTable() . "_" . __FUNCTION__ . "_" . md5(implode($dalObj->getQueryFields()));

	    if ($dalObj->getCount() == true)
		$queryCacheName .="_count";


		if ($dalObj->getCount() == true)
		    $select = "count(*) as count";
		else
		    $select = " " . SQL::ToSelect($dalObj->getOptClass(), $dalObj->getQueryFields()) . " " . $selectString . " " . $dalObj->getSelectFieldsQuery();

	    if ($dalObj->getDataArray('mf_link_destination') != false)
		$sql = " SELECT $select FROM " . $dalObj->getObjClassTable() . " INNER JOIN mf_link ON " . $dalObj->getObjClassTable() . "." . $dalObj->getObjClassTablePK() . "=mf_link.id_destination AND  mf_link.destination_type='" . $dalObj->getObjClassTable() . "' AND  mf_link.source_type='" . $dalObj->getDataArray('mf_link_table') . "' AND mf_link.id_source=" . $dalObj->getDataArray('mf_link_id');
	    else
		$sql = " SELECT $select FROM " . $dalObj->getObjClassTable() . " INNER JOIN mf_link ON " . $dalObj->getObjClassTable() . "." . $dalObj->getObjClassTablePK() . "=mf_link.id_source AND  mf_link.source_type='" . $dalObj->getObjClassTable() . "' AND  mf_link.destination_type='" . $dalObj->getDataArray('mf_link_table') . "' AND mf_link.id_destination=" . $dalObj->getDataArray('mf_link_id');

	    $sql .= " " . $joinString . " WHERE 1=1  ";
	    foreach ($dalObj->getCondition() as $key => $valueArray) {
		if ($key == "id")
		    $key = "id_" . $dalObj->getObjClassTable();
		foreach ($valueArray as $value) {
		    if (is_array($value))
			$sql .= ( is_numeric($value['value']) || $value ? " AND " . $key . " " . $value['condition'] . " " . $value['value'] : "");
		    else
			$sql .= ( is_numeric($value) || $value ? " AND " . $key . " = '" . $value . "'" : "");
		}
	    }
	    $sql .=
		    ( trim($dalObj->getGroupBy()) ? " GROUP BY " . $dalObj->getGroupBy() : "") .
		    ( trim($dalObj->getSortBy()) ? " ORDER BY " . $dalObj->getSortBy() : "") .
		    ( $dalObj->getLimit() ? " LIMIT " . $dalObj->getLimit() : "") .
		    " ";
	    try {
		$stmt = $db->prepare($sql);

		if ($dalObj->getCacheTime() > 0) {
		    $stmt->CacheStart($dalObj->getCacheTime());
		}
	    } catch (MysqlException $e) {
		
	    }
	    $stmt->execute();
	    $array = $stmt->fetchAllAssoc();

	    if ($dalObj->getCount() == true)
		return $array[0]['count'];

	    $done = array();

	    for ($i = 0; $i < count($array); $i++) {
		$className = $dalObj->getObjClassName();
		$obj = new $className();
		$obj->FromArray($array[$i], 1);

		foreach ($dalObj->getSelectFields() as $key => $value) {
		    $func = "set" . $key;
		    $obj->$func($array[$i][$key]);
		}
		if (is_array($dalObj->getJoin()))
		    foreach ($dalObj->getJoin() as $key => $value) {
			$objArray = new $key();
			$objArray->FromArray($array[$i], 1);
			$strFunciton = "set" . $key;
			$obj->$strFunciton($objArray);
		    }

		$done[$obj->GetId()] = $obj;
	    }
	    if ($dalObj->getCacheObject()) {
		self::CacheWriter($done);
	    }
	    return $done;
	} else {
	    return self::CacheReader();
	}
    }

    public static final function CacheControll(DalData $dalObj) {
	if ($dalObj->getCacheObject()) {
	    self::$cachePath = Config::Get('DBCACHE_PATH') . 'DAL/';
	    self::$cacheTime = $dalObj->getCacheTime();
	    self::$cacheId = md5(serialize($dalObj));

	    if (is_file(self::$cachePath . self::$cacheId) && filemtime(self::$cachePath . self::$cacheId) > (time() - self::$cacheTime)) {
		return true;
	    } else {
		return false;
	    }
	} else {
	    return false;
	}
    }

    public static final function CacheWriter($data) {
	$records = serialize($data);
	if (!is_dir(self::$cachePath))
	    mkdir(self::$cachePath);
	$fp = fopen(self::$cachePath . self::$cacheId, "w");
	fputs($fp, $records);
	fclose($fp);
    }

    public static final function CacheReader() {
	return unserialize(file_get_contents(self::$cachePath . self::$cacheId));
    }

    /**
     * DOdanie rekordu
     *
     * @param nazwa tablicy $objClassTable
     * @param obiekt $obj
     * @return integer
     */
    public static function DefaultInsert(DalData $dalObj) {
	$db = Registry::Get($dalObj->getDatabaseType());

	if (!is_numeric($dalObj->getObj()->getId()) || $dalObj->getObj()->getId() == -1)
	    $dalObj->getObj()->SetId('NULL');

	$sql = "INSERT INTO " . $dalObj->getObjClassTable() . " (" . SQL::ToInsertFields($dalObj->getObj()) . ") VALUES (" . SQL::ToInsertValues($dalObj->getObj()) . ")" . (is_null($dalObj->getOnDuplicateKey()) ? "" : " ON DUPLICATE KEY " . $dalObj->getOnDuplicateKey());

	$stmt = $db->prepare($sql)->execute();
	return $stmt->GetInsertionId();
    }

    /**
     * Włączenie/wyłączenie pola rekordu
     *
     * @param obiekt Dal $dalObj
     * @param nazwa pola $field
     * @return id
     */
    public static function DefaultToggleFieldById(DalData $dalObj, $field) {

	$db = Registry::Get($dalObj->getDatabaseType());

	$sql = "UPDATE " . $dalObj->getObjClassTable() . " SET `$field` = NOT `$field` WHERE " . $dalObj->getObjClassTablePK() . "=:*#1#* ";

	$stmt = $db->prepare($sql)
		->bindParam('*#1#*', $dalObj->GetId());
	$stmt->execute();

	return $dalObj->GetId();
    }

    /**
     * Aktualizacja rekordu
     *
     * @param nazwa tablicy $objClassTable
     * @param primary key tablicy $objClassTablePK
     * @param aktualizowany obiekt $obj
     */
    public static function DefaultUpdate(DalData $dalObj) {
	$db = Registry::Get($dalObj->getDatabaseType());

	$sql = "UPDATE " . $dalObj->getObjClassTable() . " SET " . SQL::ToUpdateSet($dalObj->getObj()) . " WHERE " . $dalObj->getObjClassTablePK() . "=:*#1#* ";

	$stmt = $db->prepare($sql)
		->bindParam('*#1#*', $dalObj->getObj()->GetId());

	$stmt->execute();

	return $dalObj->getObj()->GetId();
    }

    /**
     * Aktualizacja rekordu
     *
     * @param nazwa tablicy $objClassTable
     * @param primary key tablicy $objClassTablePK
     * @param tablica pol i wartosci $array
     * @param id elementu $id
     */
    public static function UpdateField(DalData $dalObj) {
	$db = Registry::Get($dalObj->getDatabaseType());

	$sql = array();

	foreach ($dalObj->getUpdateFileldArray() as $key => $value) {
	    $sql[] = $key . "='" . $db->Escape($value) . "'";
	}

	$sql = "UPDATE " . $dalObj->getObjClassName() . " SET " . implode(',', $sql) . " WHERE " . $dalObj->getObjClassTablePK() . "=:*#1#* ";

	$stmt = $db->prepare($sql)
		->bindParam('*#1#*', $dalObj->getUpdateFiledId());

	$stmt->execute();

	return $dalObj->getUpdateFiledId();
    }

    /**
     * Usuniecie rekordu
     *
     * @param nazwa tablicy $objClassTable
     * @param primary key tablicy $objClassTablePK
     * @param identyfikator rekordu $id
     */
    public static function DefaultDelete(DalData $dalObj) {
	$db = Registry::Get($dalObj->getDatabaseType());
	$sql = "DELETE FROM " . $dalObj->getObjClassTable() . " WHERE " . $dalObj->getObjClassTablePK() . "=:1";

	$stmt = $db->prepare($sql)
		->bindParam(1, $dalObj->getObj()->GetId())
		->execute();
    }

    /**
     * Usuniecie rekordu(obiektu) przy porownaniu wszystkich pol
     *
     * @param nazwa tablicy $objClassTable
     * @param primary key tablicy $objClassTablePK
     * @param identyfikator rekordu $id
     */
    public static function DefaultExactDelete(DalData $dalObj) {
	$db = Registry::Get($dalObj->getDatabaseType());
	$sql = "DELETE FROM " . $dalObj->getObjClassTable() . " WHERE " . SQL::ToDeleteSet($dalObj->getObj());
	$stmt = $db->prepare($sql)
		->execute();
    }

    /**
     * Usuniecie rekordu po nazwie pola
     *
     * @param nazwa tablicy $objClassTable
     * @param nazwa pola $field_name
     * @param identyfikator rekordu $id_mf_user
     */
    public static function DefaultDeleteByField(DalData $dalObj) {
	$db = Registry::Get($dalObj->getDatabaseType());
	$sql = "DELETE FROM " . $dalObj->getObjClassTable() . " WHERE " . $dalObj->getFieldName() . " =:1";
	$stmt = $db->prepare($sql)
		->bindParam(1, $dalObj->getId())
		->execute();
    }

    /**
     * Zwraca obiekt po numerze id
     *
     * @param nazwa opcjonalnej klasy $optClass
     * @param nazwa tablicy $objClassTable
     * @param nazwa klasy $objClassName
     * @param nazwa pola primary key $objClassTablePK
     * @param id rekordu $id
     * @return obj
     */
    public static function DefaultGetById(DalData $dalObj) {

	$dalObj->setCondition(array($dalObj->getObjClassTablePK() => array($dalObj->getId())));
	$dalObj->setLimit(1);

	$result = self::DefaultGetResult($dalObj);

	if (isset($result[0]) && is_object($result[0])) {
	    return $result[0];
	} else {
	    throw new CoreException('Brak rekordu w tablicy ' . $dalObj->getObjClassTable() . ' o id <b>' . $dalObj->getId() . '</b>!');
	}
    }

    /**
     * Wykonanie zapytania i pobranie pojedynczego obiektu
     *
     * @param DalData
     * @param bool
     * @return mixed - obiekt lub null
     */
    public static function DefaultGetObj(DalData $dalObj, $showSQL = false) {
	if ($dalObj->GetLimit() != 1) {
	    throw new UserException('Limit nie jest równy 1');
	}

	$result = self::DefaultGetResult($dalObj);

	if (is_array($result) && isset($result[0])) {
	    return $result[0];
	} else {
	    return null;
	}
    }

    /**
     * Zapisanie lub aktualizacja obiektu
     *
     * @param nazwa tablicy $objClassTable
     * @param nazwa pola primary key $objClassTablePK
     * @param aktualizoawny obiekt $obj
     */
    public static function DefaultSave(DalData $dalObj) {
	if ($dalObj->getObj()->GetId() == '-1') {
	    return self::DefaultInsert($dalObj);
	} else {
	    return self::DefaultUpdate($dalObj);
	}
    }

    public static function DefaultGetByTag(DalData $dalObj) {
	$dalObj->setCondition(array($dalObj->getObjClassTablePK() => 'mf_link.id_destination', 'mf_link.destination_type' => $dalObj->getObjClassTable(), 'wp_tag.id_wp_tag' => 'mf_link.id_source', 'mf_link.source_type' => 'wp_tag'));
	$dalObj->setJoin(array('wp_tag', 'mf_link'));

	return self::DefaultGetResult($dalObj);
    }

    public static function DefaultGetByTagSuggest(DalData $dalObj) {
	$dalObj->setCondition(array($dalObj->getObjClassTablePK() => 'mf_link.id_destination', 'mf_link.destination_type' => $dalObj->getObjClassTable(), 'wp_tag_suggest.id_wp_tag_suggest' => 'mf_link.id_source', 'mf_link.source_type' => 'wp_tag_suggest'));
	$dalObj->setJoin(array('wp_tag_suggest', 'mf_link'));

	return self::DefaultGetResult($dalObj);
    }

    public static function Save(DalData $dalObj) {
	return self::DefaultSave($dalObj);
    }

    public static function Insert(DalData $dalObj) {
	return self::DefaultInsert($dalObj);
    }

    public static function Update(DalData $dalObj) {
	return self::DefaultUpdate($dalObj);
    }

    public static function Delete(DalData $dalObj) {
	return self::DefaultDelete($dalObj);
    }

    public static function GetById(DalData $dalObj) {
	return self::DefaultGetById($dalObj);
    }

    public static function GetResult(DalData $dalObj, $showSQL = false) {
	return self::DefaultGetResult($dalObj, $showSQL);
    }

    public static function GetObj(DalData $dalObj) {
	return self::DefaultGetObj($dalObj);
    }

    public static abstract function GetDalDataObj();

    /**
     * Generator kodu JavaScript
     *
     * @param array $array
     * @param nazwa javascriptowa $jsName
     * @return string
     */
    public static function ToJavaScriptArray($array, $jsName) {
	$js = "new Array(); \n";
	foreach ($array as $key => $value) {
	    $js .= $jsName . "[" . $key . "] = '" . $value . "'; \n";
	}
	return $js;
    }

    /**
     * funkcja do js'a
     *
     * @param unknown_type $array
     * @return unknown
     */
    public static function DirectArray($array) {
	$js = "new Array(";
	foreach ($array as $value) {
	    $js .= "'$value',";
	}
	$js = substr($js, 0, -1);
	$js .= ")";

	return $js;
    }

    /*
     * Tworzy w katalogu temp klasy plik do zliczenia metoda DefaultFileCounterCountAndClean()
     */

    public static function DefaultFileCounterAppend($objClassName, $id) {
	Utils::Mkdirs(Config::Get('PATH_MAIN_APP') . '/temp/DAL/' . $objClassName);
	$fp = fopen(Config::Get('PATH_MAIN_APP') . '/temp/DAL/' . $objClassName . '/' . $id . '_' . microtime(), "w");
	fputs($fp, ' ');
	fclose($fp);
    }

    /*
     * Zwraca tablice z liczba id w katalogu temp klasy oraz usuwa pliki
     */

    public static function DefaultFileCounterCountAndClean($objClassName) {

	if (is_dir(Config::Get('PATH_STRONA_APP') . '/temp/DAL/' . $objClassName)) {

	    //$data = array();

	    if ($handle = opendir(Config::Get('PATH_STRONA_APP') . '/temp/DAL/' . $objClassName)) {
		while (false !== ($file = readdir($handle))) {
		    if ($file != "." && $file != "..") {
			$fileArray = explode('_', $file);
			//if(isset($data[$fileArray[0]])) {
			//$data[$fileArray[0]] = ($data[$fileArray[0]]+1);
			//} else {
			//$data[$fileArray[0]] = 1;
			//}

			$counter = new WpCounter();
			$counter->SetContentId($fileArray[0]);
			$counter->SetContentType($objClassName);
			$counter->SetTime(date("Y-m-d H:i:s.", filemtime(Config::Get('PATH_STRONA_APP') . '/temp/DAL/' . $objClassName . '/' . $file)));

			WpCounterDAL::Save($counter);
			//echo date("Y-m-d H:i:s.", filemtime(Config::Get('PATH_STRONA_APP').'/temp/DAL/'.$objClassName.'/'.$file));
			unlink(Config::Get('PATH_STRONA_APP') . '/temp/DAL/' . $objClassName . '/' . $file);
		    }
		}
		closedir($handle);
	    } //return $data;
	} else {
	    //return array();
	}
    }

    /**
     * Eskejpuje string.
     *
     * @param string $string
     * @return string
     */
    public static function Escape($string) {
	$db = Registry::Get('db');

	return $db->Escape($string);
    }

}
